package cn.zhentao.interceptor;

import cn.zhentao.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT令牌验证拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        
        // 登录接口不需要验证token
        if (requestURI.endsWith("/login") || requestURI.contains("/swagger") || requestURI.contains("/api-docs")) {
            return true;
        }

        // 获取Authorization头
        String authorizationHeader = request.getHeader("Authorization");
        
        if (!StringUtils.hasText(authorizationHeader) || !authorizationHeader.startsWith("Bearer ")) {
            log.warn("请求未携带有效的Authorization头: {}", requestURI);
            writeErrorResponse(response, 401, "请先登录");
            return false;
        }

        try {
            String token = authorizationHeader.substring(7);
            
            if (!JwtUtils.isValidToken(token)) {
                log.warn("无效的JWT令牌: {}", token);
                writeErrorResponse(response, 401, "登录已过期，请重新登录");
                return false;
            }

            // 将用户ID设置到请求属性中，供后续使用
            String userId = JwtUtils.getUserIdFromToken(token);
            request.setAttribute("userId", userId);
            
            log.debug("JWT令牌验证成功，用户ID: {}", userId);
            return true;
        } catch (Exception e) {
            log.error("JWT令牌验证异常", e);
            writeErrorResponse(response, 401, "令牌验证失败");
            return false;
        }
    }

    private void writeErrorResponse(HttpServletResponse response, int status, String message) throws Exception {
        response.setStatus(status);
        response.setContentType("application/json;charset=UTF-8");
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", status);
        result.put("msg", message);
        result.put("data", null);
        
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
